import { _decorator, AudioSource, BatchingUtility, Camera, Node, assetManager, Material, Vec2, v2, Prefab, v3, instantiate, Vec3, RigidBodyComponent, find, PhysicsSystem, tween, systemEvent, SystemEventType, EventTouch, CameraComponent, geometry, Touch, SkinnedMeshRenderer, MeshRenderer, Scheduler, director } from 'cc';
import BaseView from '../game/BaseView';
import GD from '../config/GD';
import GDef from '../config/GDef';
import DataManager from '../config/DataManager';
import global from '../config/global';
import { MathUtil } from '../utils/UtilsMath';
import SdkMgr from '../tyq3.x/SdkMgr';
import { tyqSDK } from '../tyq3.x/tyq-sdk';
import { EType } from '../tyq3.x/Platform/wechat/WXCustomAd';
import { MathRandom } from "../utils/UtilsMath";
import { LocalCache } from '../utils/LocalCache';
import TyqEventMgr from '../tyq3.x/tyq-event-mgr';
import Tool from '../tool/Tool'
const { ccclass, property } = _decorator;

@ccclass('gameMgr')
export class gameMgr extends BaseView {

    @property({
        type: Camera
    })
    cam: Camera = null;
    @property({
        type: Camera
    })
    camTop2D: Camera = null;
    @property({
        type: Camera
    })
    camTop2DWelcome: Camera = null;
    @property({
        type: Camera
    })
    camTop: Camera = null;
    @property({
        type: Node
    })
    nodeArms: Node = null;
    @property({
        type: Node
    })
    nodeBullets: Node = null;
    @property({
        type: Node
    })
    nodeCells: Node = null;
    @property({
        type: Node
    })
    nodeHpPanel: Node = null;
    @property({
        type: Node
    })
    nodeDamagePanel: Node = null;
    @property({
        type: Node
    })
    nodeDamagePanel: Node = null;
    @property({
        type: AudioSource
    })
    audio: AudioSource = null;
    @property({
        type: Material
    })
    materialNormalSrc: Material = null;
    @property({
        type: Material
    })
    materialLightSrc: Material = null;


    private nodeScene: Node = null;
    private nodeMain: Node = null;
    private nodeFrame: Node = null;
    private armIdCount: number = 1;
    private isFirstInit: boolean = true;

    onLoad() {
        BatchingUtility.batchStaticModel(this.node, this.node);
        TyqEventMgr.ins.sendEvent('进入游戏主界面');
        GDef.setPerf(GDef.getDeviceBench());
        this.on(GDef.wdEvent.resume, this.resumeGame);
        this.on(GDef.wdEvent.levelStart, this.levelStart);
        this.on(GDef.wdEvent.startFight, this.startFight);
        this.on(GDef.wdEvent.showEnd, this.showEnd);
        this.on(GDef.wdEvent.castHuman, this.castHuman);
        this.on(GDef.wdEvent.castDino, this.castDino);
        this.on(GDef.wdEvent.armDie, this.armDie);
        this.on(GDef.wdEvent.fightCoin, this.fightCoin);
        this.on(GDef.wdEvent.showFrameArm, this.showFrameArm);
        this.on(GDef.wdEvent.playEffect, Tool.playEffect);//播放音效

        GDef.setRoot(this.node);
        GDef.audioMgr = this.audio;
        GDef.nodeArms = this.nodeArms;
        GDef.materialNormalSrc = this.materialNormalSrc;
        GDef.materialLightSrc = this.materialLightSrc;
        GDef.setCamera(this.cam);
        GDef.setCameraTop2DWelcome(this.camTop2DWelcome);
        GDef.setCameraTop2D(this.camTop2D);
        GDef.setCameraTop(this.camTop);

        this.resumeGame();

        var self = this;
        //初始化场景
        let scene = GD.getScene();
        if (!this.nodeScene) {
            Tool.createNode(GDef.arrPackageChangjing[scene], GDef.arrPreChangjing[scene]).then((node) => {
                self.nodeScene = node;
                node.scale = v3(580, 580, 580);
                node.setPosition(v3(0, -1.5, -2.0));
                node.parent = self.node.parent;
            }).catch(err => {
                console.error(err);
            });
        }
        //初始化地图
        for (let i = 0; i < GDef.cellPos.length; i++) {
            Tool.createNode(GDef.pack1, GDef.preCell).then((node) => {
                node.setScale(v3(GDef.cellScale, GDef.cellScale, GDef.cellScale));
                node.setPosition(GDef.cellPos[i]);
                node.parent = self.nodeCells;
                if (i < 15) node.getComponent(MeshRenderer).enabled = false;
                else node.getComponent(MeshRenderer).enabled = true;
                node.getComponent("preCell").setId(i);
            }).catch(err => {
                console.error(err);
            });
        }
        //初始化UI
        Tool.createNode(GDef.pack1, GDef.preMain).then((node) => {
            self.nodeMain = node;
            self.emit(GDef.wdEvent.levelStart);
            //初始化UI
            // Tool.createNode(GDef.pack1, GDef.preEggList).then((node2) => {
            //     GDef.nodeEggList = node2;
            //     if (GDef.nodeEggList) {
            //         GDef.nodeEggList.parent = self.node;
            //         GDef.nodeEggList.active = true;//初始化首页UI
            //     }
            // }).catch(err => {
            //     console.error(err);
            // });
        }).catch(err => {
            console.error(err);
        });

    }

    start() {
        this.maxDistance = this._maxDistance;
    }


    // onEnable() {
    //     console.log("set onTouchStart.....");
    //     systemEvent.on(SystemEventType.TOUCH_START, this.onTouchStart, this);
    // }

    // onDisable() {
    //     systemEvent.off(SystemEventType.TOUCH_START, this.onTouchStart, this);
    // }
    // onTouchStart(touch: Touch, event: EventTouch) {
    //     console.log("onTouchStart.....");
    //     this.cam.screenPointToRay(touch.getLocationX(), touch.getLocationY(), this._ray);
    //     if (PhysicsSystem.instance.raycastClosest(this._ray, this._mask, this._maxDistance, false)) {
    //         console.log("hit:");
    //         const r = PhysicsSystem.instance.raycastClosestResult;
    //         const nodeHit = r.collider.node;
    //         console.log("hit:" + nodeHit.name);
    //     }
    // }
    /**初始化 */
    levelStart() {
        var self = this;
        tyqSDK.startGame(GD.getLevel());
        //如果是离线奖励
        if (GDef.nodeEnd && GDef.nodeEnd.active && GDef.nodeEnd.getComponent("preEnd").type == 0);
        //否则
        else {
            if (GD.getLevel() > 5) Tool.showTopGridAD();
            Tool.showSideGridAD();
            Tool.showBanner(false);

        }
        this.emit(GDef.wdEvent.startRay);
        if (this.nodeScene) this.nodeScene.active = true;
        this.nodeCells.active = true;
        this.nodeArms.active = true;
        this.nodeBullets.active = true;
        this.armIdCount = 1;
        GDef.intStat = 0;
        GD.resetRoundCoin();
        //摄像机
        this.cam.node.setPosition(v3(0, 4, 4.5));
        this.cam.node.eulerAngles = v3(-55, 0, 0);
        //翼龙
        let showYilong = tyqSDK.getConfigProbability('showYilong');
        if (showYilong) {
            Tool.showYiLong(this.node.parent);
        }
        else Tool.hideYiLong();
        //垃圾桶
        // Tool.showLajitong(this.node.parent);

        //初始化cell
        for (let i = 0; i < this.nodeCells.children.length; i++) {
            this.nodeCells.children[i].scale = v3(0.05, 0.05, 0.05);
        }
        //刷怪
        // let jsonBattle = jsonTables.getJsonTableObj("battle",level);
        let jsonBattle = GD.getBattle();
        for (let i = 0; i < jsonBattle.Human.length; i++) {
            let jsonHuman = jsonTables.getJsonTableObj("human", jsonBattle.Human[i]);
            let jsonArmType = jsonTables.getJsonTableObj("humanType", jsonHuman.type);
            this.initArm(this.nodeArms, GDef.SideEnemy, GDef.getHumanPos(jsonBattle.posHuman[i]), v3(0, 0, 0), jsonArmType, jsonHuman, jsonBattle.posHuman[i]);
        }
        for (let i = 0; i < jsonBattle.Dino.length; i++) {
            let jsonDino = jsonTables.getJsonTableObj("dino", jsonBattle.Dino[i]);
            let jsonArmType = jsonTables.getJsonTableObj("dinoType", jsonDino.type);
            this.initArm(this.nodeArms, GDef.SideEnemy, GDef.getDinoPos(jsonBattle.posDino[i]), v3(0, 0, 0), jsonArmType, jsonDino, jsonBattle.posDino[i]);
        }
        //我方
        for (let i = 0; i < GD.getArm().length; i++) {
            // var info: armData = {
            //     type: i == initPos ? 2:-1,//1：human表，2：dino表
            //     tid: i == initPos ? 1:-1,//表Tid
            //     pos: i,//cell的索引
            // }
            let arm = GD.getArm()[i];
            let tid = arm.tid;
            if (tid < 1) continue;
            let jsonArm = jsonTables.getJsonTableObj(arm.type == GDef.TypeHuman ? "human" : "dino", tid);
            if (!jsonArm) continue;
            let jsonArmType = jsonTables.getJsonTableObj(arm.type == GDef.TypeHuman ? "humanType" : "dinoType", jsonArm.type);
            this.initArm(this.nodeArms, GDef.SidePlayer, arm.type == GDef.TypeHuman ? GDef.getHumanPos(arm.pos) : GDef.getDinoPos(arm.pos), v3(0, 180, 0), jsonArmType, jsonArm, arm.pos);
        }
        if (this.nodeMain) {
            this.nodeMain.parent = this.node;
            this.nodeMain.active = true;//初始化首页UI
        }
        if (GDef.nodeEggList) {
            // GDef.nodeEggList.parent = this.node;
            // GDef.nodeEggList.active = true;//初始化首页UI
            // GDef.nodeEggList.getComponent("preEggList").moveIn();
        }

    }


    // parent: Node,//父节点
    // type: number,//敌我双方：1我方，2敌人
    // pos: Vec3,//位置
    // eulerAngles: Vec3//旋转角度,
    // id: number,//编号
    // Tid: number,//human或者dino表格的编号
    // prefabPackage: string,//预制体包
    // prefabPath: string,//预制体路径
    // modelPackage: string,//模型包
    // modelPath: string//模型路径
    initArm(parent: Node, type: number, pos: Vec3, eulerAngles: Vec3, jsonArmType: Object, jsonArm: Object, cellId: number) {
        var __id = this.armIdCount;
        this.armIdCount++;
        Tool.initArm(__id, parent, type, pos, eulerAngles, jsonArmType, jsonArm, cellId);
    }

    castHuman() {
        let listArm = GD.getSavedHunter();
        if (listArm.length > 0) {
            let type = GDef.TypeHuman;
            let tid = listArm[0];
            this.createArm(type, tid);
        }
    }
    castDino() {
        let listArm = GD.getSavedDino();
        if (listArm.length > 0) {
            let type = GDef.TypeDino;
            let tid = listArm[0];
            this.createArm(type, tid);
        }
    }
    createArm(type: number, tid: number) {
        let jsonArm = jsonTables.getJsonTableObj(type == GDef.TypeHuman ? "human" : "dino", tid);
        if (!jsonArm) return;
        let jsonArmType = jsonTables.getJsonTableObj(type == GDef.TypeHuman ? "humanType" : "dinoType", jsonArm.type);
        if (!jsonArmType) return;
        let cellIndex = GD.addPlayerArm(type, tid);
        if (cellIndex >= 0) {
            if (type == GDef.TypeDino) this.emit(GDef.wdEvent.playEffect, "Dinosaur_10" + Math.floor((tid - 1) / 2));
            this.initArm(this.nodeArms, GDef.SidePlayer, GDef.getHumanPos(cellIndex), v3(0, 180, 0), jsonArmType, jsonArm, cellIndex);
            Tool.playSmoke(this.nodeArms.parent, GDef.getHumanPos(cellIndex));
        }
    }
    //开始战斗
    startFight() {
        TyqEventMgr.ins.sendEvent('开始游戏');
        Tool.hideYiLong();
        // Tool.hideLajitong();
        GDef.intStat = 1;
        //初始化cell
        for (let i = 0; i < this.nodeCells.children.length; i++) {
            if (this.nodeCells.children[i]) this.nodeCells.children[i].scale = v3(0, 0, 0);
        }
        if (this.nodeMain) this.nodeMain.active = false;
        // if (GDef.nodeEggList) GDef.nodeEggList.getComponent("preEggList").moveOut();

        tween(this.cam.node).parallel(
            tween().to(0.8, { position: v3(0, 3.2, 4) }),
            tween().to(0.8, { eulerAngles: v3(-50, 0, 0) }),
        ).start();
    }
    //兵种死亡
    armDie() {
        if (GDef.intStat >= 2) return;
        var self = this;
        let player = 0;
        let enemy = 0;
        let len = this.nodeArms.children.length;
        for (let i = len - 1; i >= 0; i--) {
            if (this.nodeArms.children[i] && this.nodeArms.children[i].getComponent("preArm")?.getStat() == GDef.ArmStatAlive) {
                if (this.nodeArms.children[i].getComponent("preArm")?.side == GDef.SidePlayer) player++;
                else enemy++;
            }
        }
        //战斗结束
        if (player == 0 || enemy == 0) {
            this.emit(GDef.wdEvent.stopRay);
            tyqSDK.endGame(enemy == 0);

            Tool.hideTopGridAD();
            Tool.hideSideGridAD();
            Tool.hideBanner();

            //战斗结束
            //胜利
            if (enemy == 0) {
                GDef.intStat = 2;
                this.scheduleOnce(() => {
                    Tool.playPD(self.node);
                }, 0.5);
                this.emit(GDef.wdEvent.playEffect, "Victory");
                this.emit(GDef.wdEvent.levelWin);
            }
            //失败
            else {
                GDef.intStat = 3;
                this.emit(GDef.wdEvent.playEffect, "Lose");
                this.emit(GDef.wdEvent.levelLose);
            }
            this.countTime = new Date().getTime();
            this.scheduleOnce(() => {
                // let switchCastSpecial = tyqSDK.getConfigProbability('tyq_returnMain');
                // if(getSwitchValue)

                //随机显示激励视频
                let t = tyqSDK.getSwitchValue("tyq_video_interval");
                if (t > 0 && GD.getLevel() % t == 0) {
                    SdkMgr.ins.showRewardAd("观看激励视频-完成任意局数", () => {
                        GDef.intRewardTime = new Date().getTime();
                    }, () => {
                        GDef.intRewardTime = new Date().getTime();
                    }, () => {
                        GDef.intRewardTime = new Date().getTime();
                    })
                }

                //显示全屏的矩阵广告
                if (GDef.nodeContinue) {
                    GDef.nodeContinue.parent = GDef.getCameraTop2DWelcome().node.parent;
                    GDef.nodeContinue.active = true;
                    Tool.showGridAD();
                    SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.mainLayerTop, EType.horizontal, {
                        top: 0,
                    });
                }
                else {
                    Tool.createNode(GDef.pack1, GDef.preContinue).then((node) => {
                        GDef.nodeContinue = node;
                        GDef.nodeContinue.parent = GDef.getCameraTop2DWelcome().node.parent;
                        GDef.nodeContinue.active = true;
                        Tool.showGridAD();
                        SdkMgr.ins.showWxCustomAd(GDef.wxGridFlag.mainLayerTop, EType.horizontal, {
                            top: 0,
                        });
                    }).catch(err => {
                        console.error(err);
                    });
                }

            }, 1);
        }
    }
    showEnd() {
        //显示结算界面
        let self = this;
        if (GDef.nodeEnd) {
            self.showEndCallback();
        }
        else {
            Tool.createNode(GDef.pack1, GDef.preEnd).then((node) => {
                GDef.nodeEnd = node;
                self.showEndCallback();
            }).catch(err => {
                console.error(err);
            });
        }
    }
    showEndCallback() {
        let self = this;
        self.scheduleOnce(() => {
            GDef.nodeEnd.active = true;
            GDef.nodeEnd.parent = self.node;
            GDef.nodeEnd.getComponent("preEnd").init(GDef.intStat == 2 ? 1 : 2);


            // self.nodeCells.active = false;
            // self.nodeScene.active = false;
            // self.nodeArms.active = false;
            // self.nodeBullets.active = false;
            //清理战场
            let len = self.nodeArms.children.length;
            for (let i = len - 1; i >= 0; i--) {
                if (i < self.nodeArms.children.length && self.nodeArms.children[i]) GDef.poolArm.put(self.nodeArms.children[i]);
            }

            //预加载资源
            if (this.isFirstInit) {
                this.isFirstInit = false;
                assetManager.loadBundle("AudioClip", function (err, bundle) {
                    if (err) {
                        console.log('pack1分包加载失败')
                        return;
                    }
                });
                assetManager.loadBundle("pack2", function (err, bundle) {
                    if (err) {
                        console.log('pack1分包加载失败')
                        return;
                    }
                    bundle.preloadDir('prefab', Prefab);
                });
                assetManager.loadBundle("Dino2", function (err, bundle) {
                    if (err) {
                        console.log('Dino2分包加载失败')
                        return;
                    }
                });
                assetManager.loadBundle("Dino7", null);
                assetManager.loadBundle("Hunter2", null);
                assetManager.loadBundle("Hunter3", null);
                assetManager.loadBundle("Hunter4", null);
                assetManager.loadBundle("Hunter5", null);
                assetManager.loadBundle("Hunter6", null);
                assetManager.loadBundle("Hunter7", null);
                assetManager.loadBundle("Hunter8", null);
            }

        }, Math.min(1, 1 - (new Date().getTime() - self.countTime) / 1000));
    }
    //统计战斗得到的金币
    fightCoin(num: number) {
        GD.addRoundCoin(num);
    }
    //弹窗
    showFrameArm(type: number, tid: number, num: number = 0) {
        GDef.eventListShowFrame.push({ "type": type, "tid": tid, "num": num });
        var self = this;
        if (this.nodeFrame && GDef.getCameraTop2D().node.parent.getChildByName("preFrame")) return;
        Tool.createNode(GDef.pack2, GDef.preFrame).then((node) => {
            if (this.nodeFrame && GDef.getCameraTop2D().node.parent.getChildByName("preFrame")) return;
            self.nodeFrame = node;
            node.parent = GDef.getCameraTop2D().node.parent;
            node.getComponent("preFrame").show(GDef.eventListShowFrame[0]["type"], GDef.eventListShowFrame[0]["tid"], GDef.eventListShowFrame[0]["num"]);
            GDef.eventListShowFrame.splice(0, 1);
        }).catch(err => {
            console.error(err);
        });
    }
    resumeGame() {
        let offset = new Date().getTime() - GD.getOnlineTime();
        //5分钟
        let self = this;
        console.log("offset:" + offset);
        if (offset > 300000) {
            GD.setRoundCoin(Math.floor(offset / 60000) * GD.getLevel() * 2);
            //显示结算界面
            if (GDef.nodeEnd) {
                self.showWelcome();
            }
            else {
                Tool.createNode(GDef.pack1, GDef.preEnd).then((node) => {
                    GDef.nodeEnd = node;
                    self.showWelcome();
                }).catch(err => {
                    console.error(err);
                });
            }
        }
    }
    showWelcome() {
        GDef.nodeEnd.active = true;
        GDef.nodeEnd.parent = this.camTop2D.node.parent;
        GDef.nodeEnd.getComponent("preEnd").init(0);
    }
}
